<template>
  <a-form :form="form">
    <a-form-item
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        label="品牌名称"
    >
      <a-input
          v-decorator="[
          'unit.name',
          { rules: [{ required: true, message: '请输入品牌名称' }] },
        ]"
          placeholder="请输入品牌名称"
      />
    </a-form-item>
    <a-form-item label="品牌搜索标签"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-select
          mode="tags"
          :size="size"
          placeholder="可输入多个品牌搜索标签"
          style="width: 100%"
          v-decorator="[
          'unit.tags',
          { rules: [{ required: true, message: '请输入品牌搜索标签' }] },
        ]"
      >
      </a-select>
    </a-form-item>
    <a-form-item label="品牌图标"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-upload
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadApi"
          :headers="{Authorization: `Bearer ${token}`}"
          :before-upload="beforeUpload"
          @change="handleChange"
          :disabled="loading"
          v-decorator="[
          'unit.image',
          { rules: [{ required: true, message: '请上传品牌图标' }] },
        ]"
      >
        <img v-if="unit.image" :src="unit.image" alt="avatar" class="img-up"/>
        <div v-else>
          <a-icon :type="loading ? 'loading' : 'plus'" />
          <div class="ant-upload-text"></div>
        </div>
      </a-upload>
    </a-form-item>

    <a-form-item label="排序"
                 :label-col="formItemLayout.labelCol"
                 :wrapper-col="formItemLayout.wrapperCol">
      <a-input-number id="inputNumber" :min="0" @change="onChange" v-decorator="[
          'unit.sorts',{ initialValue: 0 },
        ]" />
    </a-form-item>
    <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol">
      <a-button type="primary" @click="check">
        提交
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import code from '@/common/code'
import {getBrandDetail,editBrand} from '@/api'
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 8 },
};
const formTailLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 8, offset: 4 },
};
export default {
  name: "brand-edit",
  data() {
    return {
      unit:{
        name:'',
        tags:[],
        sorts:0,
        image:''
      },
      token:localStorage.getItem('token')||'',
      uploadApi: '/admin-api/common/uploadFile',
      loading: false,
      imageUrl: '',
      value: 1,
      size:'default',
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this, { name: 'dynamic_rule' }),
    };
  },
  methods: {
    onChange(value) {
    },
    //提交
    check() {
      this.form.validateFields(async (err,values)=> {
        if (!err) {
          console.info('success');
          if (this.$route.query.id) {
            values.unit.id = this.$route.query.id
          }
          let tags = values.unit.tags.join(',')
          if (tags.length > 32) {
            this.$message.error('品牌搜索标签字数太多')
            return
          }
          values.unit.tags = tags
          values.unit.image = this.unit.image
          await editBrand(values.unit)
          this.$message.success('操作成功')
          this.$router.push('/shop/brand')
        }
      });
    },
    handleChange (e) {
      if (e.file.status === 'done') {
        if (e.file.response.code === code.SUCCESS) {
          this.unit.image = e.file.response.value
          // this.$emit('change', this.imageUrl)
        } else {
          this.$message.error(e.file.response.message)
        }
        this.loading = false
      }

    },
    beforeUpload (file) {
      this.loading = true
      const the = this
      return new Promise((resolve, reject) => {
        const url = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function () {
          const { width, height } = img
          the.loading = false
          // 校验格式
          if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            the.$message.error('请上传JPG,PNG格式')
            reject(false)
          }

          // 校验大小
          if (file.size > this.maxSize * 1024 * 1024) {
            the.$message.error(`不得大于${this.maxSize}M`)
            reject(false)
          }

          // 校验比例
          if (the.proportion && ratio(width, height).toString() !== the.proportion) {
            the.$message.error('图片比例不正确')
            reject(false)
          }

          // 校验尺寸
          if ((the.fixedWidth && the.fixedWidth !== width) || (the.fixedHeight && the.fixedHeight !== height)) {
            the.$message.error('图片尺寸不正确')
            reject(false)
          }
          resolve(file)
        }
        img.src = url.createObjectURL(file)
      })
    },
    //品牌详情
    async getBrandDetailFn(){
     const res= await getBrandDetail(this.$route.query.id)
      this.unit=res.value
      this.unit.tags = res.value.tags.split(',')
      this.form.setFieldsValue({
        'unit.name': this.unit.name,
        'unit.tags': this.unit.tags,
        'unit.sorts': this.unit.sorts,
        'unit.image': this.unit.image,
      });
    }
  },
  mounted(){
    if(this.$route.query.id){
      this.getBrandDetailFn()
    }

  }
};
</script>


<style scoped lang="less">

.img-up{
  width: 100%;
  height: 100%;
}
</style>
